package wassalt.client;

import java.util.ArrayList;

import wassalt.Utils.AppConstants;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class LoadContactActivity extends ListActivity implements OnClickListener{

	FavoriteClientsAdapter la;
	ListView lv;
	Cursor c;
	Button done;
	Button cancel;
	String[] menu_items;
	String n;
	String p;
	ContentResolver cr;
	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.favorites);
		setTitle(getString(R.string.all_contacts));

		//Fetch all contacts which have at least one phone number
		cr = getContentResolver();
		final String[] projection = { BaseColumns._ID, 
				ContactsContract.Contacts.DISPLAY_NAME, 
				ContactsContract.Contacts.HAS_PHONE_NUMBER};
		final String condition = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'";
		final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		c = cr.query(ContactsContract.Contacts.CONTENT_URI,
				projection, condition, null, sortOrder);

		//Generate the list
		la = new FavoriteClientsAdapter(this, c, AppConstants.ALL);
		setListAdapter(la);

		//View the table in a list view
		lv = getListView();
		lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		//Set the onClick listener for the list items
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int pos,
					long id) {
				itemClick(v);
			}
		});

		lv.setTextFilterEnabled(true);
		lv.setItemsCanFocus(false);

		initializeSearchBar();

		//Set the onClick Listeners for the buttons
		done = (Button) findViewById(R.id.favorites_done);
		done.setEnabled(false);
		done.setOnClickListener(this);
		cancel = (Button) findViewById(R.id.favorites_cancel);
		cancel.setOnClickListener(this);
	}

	/**
	 * Configure the text field to filter the contents of the list view according
	 * to what is written in the text field
	 * @author Aya Kamel
	 */
	private void initializeSearchBar()
	{
		EditText searching = (EditText) findViewById(R.id.searchField);
		searching.addTextChangedListener(
				new TextWatcher(){

					@Override
					public void afterTextChanged(Editable arg0){
						// After text settles fetch all contacts whose names
						// contain the string typed in the search box
						final String[] projection = { BaseColumns._ID, 
								ContactsContract.Contacts.DISPLAY_NAME, 
								ContactsContract.Contacts.HAS_PHONE_NUMBER};
						final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
						if(arg0 != null && !arg0.toString().equals(""))
						{
							final String condition = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' "+
									"AND "+ContactsContract.Contacts.DISPLAY_NAME +" LIKE ?";
							final String[] delimiters = new String[]{"%"+arg0.toString()+"%"};
							c = cr.query(ContactsContract.Contacts.CONTENT_URI,
									projection, condition, delimiters, sortOrder);
						}
						else
						{
							final String condition = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' ";
							c = cr.query(ContactsContract.Contacts.CONTENT_URI,
									projection, condition, null, sortOrder);
						}
						
						la.changeCursor(c);
					}

					@Override
					public void beforeTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onTextChanged(CharSequence arg0, int arg1,
							int arg2, int arg3) {
						// TODO Auto-generated method stub

					}
				});
	}

	/**
	 * Whenever a list is clicked, the corresponding check box is checked
	 * @param View
	 * 		The view in the index of the clicked item
	 * @author Aya Kamel
	 */
	private void itemClick(View v) {
		// TODO Auto-generated method stub
		TextView phn = (TextView)v.findViewById(R.id.contact_phone);
		TextView n = (TextView)v.findViewById(R.id.contact_name);
		String phone_num = (String) phn.getText();
		String name = (String) n.getText();
		if(phone_num.contains(",")) //more than one number
		{
			askForOneNumber(phone_num, name);
		}
		else //only one number
		{
			if(!phone_num.equals(""))
				Select(name, phone_num);
		}
	}

	/**
	 * Selects/Checks the contact of name and phone
	 * @author Aya Kamel
	 * @param name
	 * 		The name of the contact
	 * @param phone
	 * 		The phone number of the contact
	 */
	private void Select(String name, String phone)
	{
		la.check(phone, name);
		int selected_items = la.getNumSelected();
		String text = getString(R.string.done);
		if(selected_items>0)
		{
			done.setEnabled(true);
			text += " ("+selected_items+")";
		}
		else
		{
			done.setEnabled(false);
		}
		done.setText(text);
		la.notifyDataSetChanged();
	}

	/**
	 * Prompts the user to choose a number from many options if
	 * more than one phone number exists for a certain contact
	 * @author Aya Kamel
	 * @param phone_num
	 * 		The string containing the concatenated phone numbers
	 * @param name
	 * 		The name of the contact whose number will be selected
	 */
	private void askForOneNumber(String phone_num, String name) {

		menu_items = phone_num.split(", ");
		n = name;

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.window_title));

		builder.setItems(menu_items, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int item) {
				p = menu_items[item];
				Select(n, p);
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onPause()
	 */
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		Log.i("Activity", "Paused");
		super.onPause();
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	/**
	 * @author Aya Kamel
	 * @see android.app.Activity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}

	/**
	 * Creates a new bundle and inserts the names and phones of chosen contacts
	 * and returns this bundle in an intent with a success message
	 * @author Aya Kamel
	 */
	@Override
	public void finalize()
	{
		Bundle b = new Bundle();
		Intent intent = new Intent();
		ArrayList<String> names = new ArrayList<String>();
		ArrayList<String> phones = new ArrayList<String>();

		for (int i=0; i<la.selected.size(); i++) {
			String name = la.selected.get(i).getName();
			String phone = la.selected.get(i).getPhone();
			names.add(name);
			phones.add(phone);
			Log.i("Favorites", "Position "+i+": ("+name+", "+phone+")");
		}

		la.selected.clear();
		b.putStringArrayList("SelectedNames", names);
		b.putStringArrayList("SelectedPhones", phones);
		intent.putExtras(b);
		setResult(AppConstants.SUCCESS, intent);
		finish();
	}

	/**
	 * Creates an empty intent with a failure message
	 * @author Aya Kamel
	 */
	public void returnEmpty()
	{
		la.selected.clear();
		Intent intent = new Intent();
		setResult(AppConstants.FAILURE, intent);
		finish();
	}

	/**
	 * Captures the clicks of the buttons and chooses the right
	 * action according to the clicked button
	 * @author Aya Kamel
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == done)
			finalize();
		if(v == cancel)
			returnEmpty();
	}

}